package com.kk.gray.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.utils.StringUtils;
import com.kk.gray.pojo.EnvProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

/*
 * @Description:    网关
 * @Author:         阿K
 * @CreateDate:     2022/12/1 23:26
 * @Param:
 * @Return:
**/
@Component
@RefreshScope
public class GrayscaleGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    EnvProperties envProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest ( );
        ServerHttpResponse response = exchange.getResponse ( );
        HttpHeaders header = response.getHeaders ( );
        header.add ("Content-Type", "application/json; charset=UTF-8");

        // 拿到请求头的 userId
        List<String> list = request.getHeaders ( ).get ("userId");
        if (Objects.isNull (list) || list.isEmpty ( )) {
            return resultErrorMsg (response, " 缺少userId！");
        }

        String userId = list.get (0);
        if (StringUtils.isBlank (userId)) {
            return resultErrorMsg (response, " 缺少userId！");
        }
        if (envProperties.getGrayUsers ( ).contains (userId)) {
            //指定灰度版本
            GrayscaleThreadLocalEnvironment.setCurrentEnvironment (envProperties.getGrayVersion ( ));
        } else {
            //指定生产版本
            GrayscaleThreadLocalEnvironment.setCurrentEnvironment (envProperties.getProVersion ( ));
        }
        return chain.filter (exchange.mutate ( ).request (request).build ( ));
    }

    private Mono<Void> resultErrorMsg(ServerHttpResponse response, String msg) {
        JSONObject jsonObject = new JSONObject ( );
        jsonObject.put ("code", "403");
        jsonObject.put ("message", msg);
        DataBuffer buffer = response.bufferFactory ( ).wrap (jsonObject.toJSONString ( ).getBytes ( ));
        return response.writeWith (Mono.just (buffer));
    }

    // 优先级，越少越大(当前过滤器的优先级
    @Override
    public int getOrder() {
        return -1;
    }
}
